<?php

namespace app\order\logic;

use app\common\library\RedissLock;
use app\common\service\CommonSystemImportService;
use app\data\util\HttpUtil;
use think\facade\Db;
use think\facade\Cache;
use think\exception\ValidateException;
use think\facade\Log;
use util\Token;
use util\Upload;

use app\common\library\Excel;
use app\data\util\MqQueueName;
use app\systems\logic\MqTaskPushLogic;

class OrderCheckLogisticsLogic extends BasicLogic
{
    protected $model = null;
    public function __construct()
    {
        $this->model = new \app\order\model\OrderCheck();
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 列表
     * @author zhangheng
     */
    public function index($params = [])
    {
        $date          = $params['date'] ?? [];
        $channels      = $params['channels'] ?? "";
        $limit         = $params['limit'] ?? 10;
        $where         = [];
        
        if(!empty($ordercheck_id)){
            $where['ordercheck_id'] = $ordercheck_id;
        }
        if(!empty($date)){
            $where[]  = ['date', '>=', $date[0]];
            $where[]  = ['date', '<=', $date[1]];
        }
        if($channels){
            $where[] = array('tracking_company_number', '=',$channels);
        }

        $list = Db::name('ordercheck_logistics')
            ->where($where)
            ->order("id asc")
            ->paginate($limit);

        $lists = $list->items();
        $arr_status = [0=>'匹配中',1=>'已完成'];
        foreach ($lists as $k=>$v) {
            $lists[$k]['status'] = $arr_status[$v['status']];
        }
                
        $data = [
            'list' => $lists,
            'total' => $list->total(),
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }

    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 导出
     * @author zhangheng
     */
    public function export($params = [])
    {
        $lists = [];
        $header = [];
        $header[] = ['月份', 'date'];
        $header[] = ['支付类型', 'type'];
        $header[] = ['转单号码', 'transfer_number'];
        $header[] = ['金额', 'cost'];
        $fileName = "export_Advaccount" . time();
        return Excel::exportData($lists, $header, $fileName, 'xlsx');
    }

    public function add($data = [])
    {
        if (!$data) {
            return json(DefaultResponse(201, false, '参数不能为空!', null));
        }
        if (!$data['date']) {
            return json(DefaultResponse(201, false, '请填写月份!', null));
        }
        if (!$data['type']) {
            return json(DefaultResponse(201, false, '请填写类型!', null));
        }
        $row = Db::name('ordercheck')
            ->where('date',$data['date'])
            ->where('type',$data['type'])
            ->find();
        if ($row) {
            return json(DefaultResponse(201, false, '已存在任务!', null));
        }

        $result = false;

        try {
            //广告账户
            $ordercheck['date'] = $data['date'];
            $ordercheck['time'] = strtotime($data['date']);
            $ordercheck['type'] = $data['type'];
            $ordercheck['status'] = $data['status'] ?? 0;

            $result = Db::name('ordercheck')->insert($ordercheck);
            if ($result !== false) {
                return json(DefaultResponse(200, true, '添加成功!', null));
            } else {
                return json(DefaultResponse(201, false, '添加失败!', null));
            }
        } catch (ValidateException $e) {
            return json(DefaultResponse(201, false, $e->getError(), null));
        } catch (\Exception $e) {
            return json(DefaultResponse(201, false, '广告账户已存在!', null));
        }
        return json(DefaultResponse(200, false, '更新成功!', null));

    }

    public function find($id)
    {
        if (!$id) {
            return json(DefaultResponse(201, false, '参数不能为空!', null));
        }
        $row = $this->model->find($id);
        
        if (empty($row)) {
            return json(DefaultResponse(201, false, '数据不存在!', null));
        }

        switch ($row['type']) {
            case '1':
                $row['type'] = '争议成本';
                break;
            case '2':
                $row['type'] = '物流成本';
                break;
            case '3':
                $row['type'] = '采购成本';
                break;
            default:
                $row['type'] = '未知';
        }

        return json(DefaultResponse(200, true, '获取成功', $row));
    }

    public function edit($data = [])
    {
        if (!$data) {
            return json(DefaultResponse(201, false, '参数不能为空!', null));
        }
        $id = $data['id'];
        $row = $this->model->find($id);
        if (empty($row)) {
            return json(DefaultResponse(201, false, '数据不存在!', null));
        }
        $result = false;

        try {
            
            //广告账户
            $ordercheck['status'] = $data['status'] ?? 0;
            $result = $row->save($ordercheck);

            if ($result) {
                return json(DefaultResponse(200, false, '更新成功!', null));
            }
            return json(DefaultResponse(201, false, '更新失败!', null));
        } catch (ValidateException $e) {
            return json(DefaultResponse(201, false, $e->getError(), null));
        } catch (\Exception $e) {
            return json(DefaultResponse(201, false, '更新失败!', null));
        }
        return json(DefaultResponse(200, false, '更新成功!', null));
    }
    





    /**
     * @param $params
     * @return \think\response\Json
     * @throws \think\db\exception\DbException
     * @desc 渠道列表
     * @author zhangheng
     */
    public function ChannelsList($params = [])
    {
        $data = [  
            ['value' => '递四方', 'label' => '递四方'],  
            ['value' => '闪电猴', 'label' => '闪电猴'],  
            ['value' => '顺丰国际', 'label' => '顺丰国际'],
            ['value' => '燕文专线', 'label' => '燕文专线'],  
            ['value' => '全程无忧', 'label' => '全程无忧'],  
        ];
        return json(DefaultResponse(200, true, '获取成功', $data));
    }


    /**
     * @desc 顺丰3月账单对账
     * @author  luckyXiong
     */
    public function import_SF_detail($params){
        try{
            $result = CommonSystemImportService::staticModel()->operate_import_data([
                    $this,//当前对应的service
                    'save',//类型: template 下载模板; save :保存 导入
                    CommonSystemImportService::TYPE_IMPORT_SF_PAGE,
                    1,
                    $params
                ]
            );
        }catch (\Exception $e) {
            return $this->jsonMessage(201, false, $e->getMessage(), null);
        }
    }


    /**
     * @desc 将导入数据写入目标表
     * @author xx
     * @date 2024-03-21
     */
    public function import_sf_info($params=[]){
        $key        = 'import_sf_info:'.time();
        $redis_lock = new RedissLock();
        $lock       = $redis_lock::lock($key, $redis_lock::UNBLOCK, 30);
      //  $reference_no             = getIsset($params,'reference_no');
        $waybill_no               = getIsset($params,'waybill_no');
        $postal                   = getIsset($params,'postal');
        $total_weight             = getIsset($params,'total_weight');
        $pieces                   = getIsset($params,'pieces');
        $operating_fee            = getIsset($params,'operating_fee');
        $service_fee              = getIsset($params,'service_fee');
        $createtime               = getIsset($params,'createtime');
        $zone_id                  = getIsset($params,'zone_id');
        $code                     = getIsset($params,'code');
        $reference_no             = Db::name('order')->where('tracking_number',$waybill_no)->value('order_id');
        //数据入库逻辑
        $info = [
            'reference_no'        =>$reference_no,
            'waybill_no'          =>$waybill_no,
            'postal'              =>$postal,
            'zone_id'             =>$zone_id,
            'total_weight'        =>$total_weight,
            'pieces'              =>$pieces,
            'operating_fee'       =>$operating_fee,
            'code'                =>$code,
        ];
        Db::name('checkbill_sf')->insert($info);
        if($waybill_no){
            $create_time = date('Y-m-d H:i:s',strtotime($createtime));
            $date        = '2024-12';
            //同时写入运费总表中
            $inser_data  =
                [
                    'transfer_number'              => $waybill_no,
                   // 'freight'                      => $operating_fee+$service_fee,
                    'freight'                      => 0,
                    'tracking_company_number'      => 4,
                    'date'                         => $date,
                    'createtime'                   => $create_time,
                    'weight'                       => $total_weight*1000,
                ];
            Db::name('ordercheck_logistics')->insert($inser_data);

            //同时写入订单表中;
            $update_order_data =
                [
                   // 'freight'                      => $operating_fee+$service_fee,
                    'freight'                      => 0,
                    'freight_weight'               => $total_weight*1000,
                ];
            Db::name('order_achievement')->where('order_id',$reference_no)->update($update_order_data);
        }
        $lock->unlock();
        $info['status'] = 1;
        return  $info;
    }


    /**
     * @desc 将导入数据写入目标表
     * @author xx
     * @date 2024-10-17
     */
    public function import_sf_fee_info($params=[]){
        $key        = 'import_sf_fee_info:'.time();
        $redis_lock = new RedissLock();
        $lock       = $redis_lock::lock($key, $redis_lock::UNBLOCK, 500);
        $reference_no             = getIsset($params,'reference_no');
        $waybill_no               = getIsset($params,'waybill_no');
        $postal                   = getIsset($params,'postal');
        $total_weight             = getIsset($params,'total_weight');
        $pieces                   = getIsset($params,'pieces');
        $operating_fee            = getIsset($params,'operating_fee');
        $freight                  = getIsset($params,'freight');
        $createtime               = getIsset($params,'createtime');
        $zone_id                  = getIsset($params,'zone_id');
        $code                     = getIsset($params,'code');
        $reference_no             = Db::name('order')->where('tracking_number',$waybill_no)->value('order_id');
        //数据入库逻辑
        $info = [
            'reference_no'        =>$reference_no,
            'waybill_no'          =>$waybill_no,
            'postal'              =>$postal,
            'zone_id'             =>$zone_id,
            'total_weight'        =>$total_weight,
            'pieces'              =>$pieces,
            'operating_fee'       =>$operating_fee,
            'code'                =>$code,
        ];

        Db::name('checkbill_sf_fee')->insertGetId($info);
        $lock->unlock();
        $info['status'] = 1;
        return  $info;
    }


    /**
     * @param $row
     * @return string[]
     * @desc 数据title 导入组装数据结构
     */
    public function get_excel_row_data($row){
        return [
            'waybill_no'         => empty($row['C'])?  '': trim($row['C']),
            'total_weight'       => empty($row['J'])? '': trim($row['J']),
            'pieces'             => 1,
            'operating_fee'      => empty($row['P'])? '': trim($row['P']),
            'createtime'         => empty($row['S'])? '': trim($row['S']),
        ];



    }

}
